package jp.co.neosystem.adwg.neodiary.db.dao;

import java.util.ArrayList;
import java.util.List;

import jp.co.neosystem.adwg.neodiary.db.entity.Diary;
import jp.co.neosystem.adwg.neodiary.db.util.OrderByMap;
import jp.co.neosystem.adwg.neodiary.db.util.WhereMap;
import jp.co.neosystem.adwg.neodiary.util.TimestampUtil;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * <pre>
 * 日記テーブルDao
 * 
 * <pre>
 * 
 * @author NEOSystem
 */
public class DiaryDao extends AbstractDao<Diary>
{
	/**
	 * コンストラクタ
	 * 
	 * @param context
	 */
	public DiaryDao(Context context)
	{
		super(context);
	}

	/**
	 * 
	 */
	public List<Diary> select()
	{
		return select(null, null);
	}

	public List<Diary> select(WhereMap whereMap, OrderByMap orderByMap)
	{
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		int count = 0;

		List<Diary> diarys;
		try
		{
			Cursor cursor = db.query(Diary.TABLE_NAME, null, whereMap == null ? null : whereMap.getWhere(), whereMap == null ? null : whereMap.getWhereValues(), null, null, orderByMap == null ? null : orderByMap.getOrderBy());

			diarys = new ArrayList<Diary>();
			cursor.moveToFirst();
			while (!cursor.isAfterLast())
			{
				Diary diary = new Diary();
				diary.set_id(cursor.getInt(0));
				diary.setDate(cursor.getString(1));
				diary.setTitle(cursor.getString(2));
				diary.setContent(cursor.getString(3));
				diary.setInsert_date(cursor.getString(4));
				diary.setUpdate_date(cursor.getString(5));
				diarys.add(diary);
				cursor.moveToNext();
				count++;
			}

			Log.d(this.getClass().getSimpleName(), "count [" + count + "]");
		}
		finally
		{
			db.close();
		}

		return diarys;
	}

	public void insert(Diary entity)
	{
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		try
		{
			ContentValues values = new ContentValues();
			values.put(Diary.COLUMN_NAME_DATE, entity.getDate());
			values.put(Diary.COLUMN_NAME_TITLE, entity.getTitle());
			values.put(Diary.COLUMN_NAME_CONTENT, entity.getContent());
			values.put(Diary.COLUMN_NAME_INSERT_DATE, TimestampUtil.getTimestamp());
			values.put(Diary.COLUMN_NAME_UPDATE_DATE, TimestampUtil.getTimestamp());

			db.insert(Diary.TABLE_NAME, null, values);
		}
		finally
		{
			db.close();
		}
	}

	public void update(Diary entity, WhereMap where)
	{
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		try
		{

		}
		finally
		{
			db.close();
		}
	}

	public void delete(WhereMap where)
	{
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		try
		{

		}
		finally
		{
			db.close();
		}
	}
}
